package cn.bjit.mq;

import cn.bjit.model.ProductMessage;
import cn.bjit.service.ProductService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {
    @Resource
    private ProductService productService;
    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Message message, Channel channel) throws IOException {
       log.info("消息是{}",productMessage);

        long msgId = message.getMessageProperties().getDeliveryTag();
        //释放商品库存
       boolean flag= productService.releaseProductStock(productMessage);
       try{
            if(flag){
                //确认消费成功！
                channel.basicAck(msgId,false);
                
            }else{
                channel.basicReject(msgId,true);
            }
       }catch (IOException e){
           log.error("释放商品库存异常:{},msg:{}", e, productMessage);
           channel.basicReject(msgId, true);
       }
    }
    @RabbitHandler
    public void releaseProductStock2(String msg,Message message, Channel channel) throws IOException {
        log.info(msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
    }

}
